<?php

namespace app\admin\controller\auth;

use app\admin\model\AdminLog as AdminLogModel;
use app\common\controller\Backend;
use think\db\exception\DbException;

/**
 * 管理员登录日志
 */
class AdminLog extends Backend
{
    /**
     * @var AdminLogModel
     */
    protected $model = null;

    protected $preExcludeFields = ['create_time', 'admin_id', 'username'];

    protected $quickSearchField = ['title'];

    /**
     * 查看请求返回的主表字段控制
     */
    protected $indexField = ['id', 'username', 'url', 'title', 'ip', 'create_time'];

    public function initialize()
    {
        parent::initialize();
        $this->model = new AdminLogModel();
    }

    /**
     * 查看
     */
    public function index()
    {
        $this->request->filter(['strip_tags', 'trim']);
        if (stringToBoolean($this->request->param('select'))) {
            $this->select();
        }

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        if (!$this->auth->isSuperAdmin()) {
            $where[] = ['admin_id', '=', $this->auth->id];
        }
        try {
            $res   = $this->model
                ->field($this->indexField)
                ->withJoin($this->withJoinTable, $this->withJoinType)
                ->alias($alias)
                ->where($where)
                ->order($order)
                ->paginate($limit);

            $this->success('', [
                'list'   => $res->items(),
                'total'  => $res->total(),
                'remark' => get_route_remark(),
            ]);
        } catch (DbException $ex) {
            $this->success('', [
                'list'   => [],
                'total'  => 0,
                'remark' => get_route_remark(),
            ]);
        }
    }

    /**
     * 查看详情
     * @param null $id
     */
    public function info($id = null)
    {
        if (empty($id)) {
            $this->error(__('Record not found'));
        }
        $row = [];
        try {
            // 查询管理员信息
            $row   = $this->model->find($id);
        } catch (DbException $ex) {
            $this->error(__('Record not found'));
        }
        if (empty($row)) {
            $this->error(__('Record not found'));
        }
        $this->success('', [
            'row' => $row
        ]);
    }
}
